﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CourseSystem.Common.Helpers;
using CourseSystem.Common.Models;

namespace CourseSystem.Common.Chat
{
    public class ChatHelper
    {
        public static List<ChatModel> ChatList;
        public static Dictionary<UserModel, DateTime> OnlineChatDic;
        static ChatHelper()
        {
            ChatList = new List<ChatModel>(500);
            OnlineChatDic = new Dictionary<UserModel, DateTime>(10);
            //OnlineChatDic.Add(userh)
        }

        public static void AddMessage(string message)
        {
            var add = new ChatModel
                          {
                              Message = message,
                              Name = UserHelper.LoginUser.UserName,
                              SendTime = DateTime.Now,
                              Type = (int)UserHelper.LoginUser.UserType
                          };
            AddMessage(add);
        }

        public static void AddMessage(ChatModel info)
        {
            AddOnline();
            if (ChatList.Count > 500)
                ChatList.RemoveAt(0);
            ChatList.Add(info);
        }

        public static void AddOnline()
        {
            var user = UserHelper.LoginUser;
            if (user == null||(int)user.UserType==3)
                return;
            var now = DateTime.Now;

            DateTime onlineInfo;
            if (OnlineChatDic.TryGetValue(user, out onlineInfo))
                OnlineChatDic[user] = now;
            else
                OnlineChatDic.Add(user, now);
            //ClearUnOnline();

        }

        public static void ClearUnOnline()
        {
            var now = DateTime.Now;
            for (int i = 0; i < OnlineChatDic.Count; i++)
            {
                var item = OnlineChatDic.ElementAt(i);
                if (item.Value.AddMinutes(1.5) < now)
                {

                    OnlineChatDic.Remove(item.Key);
                }
            }
        }
    }
}
